//
// Created by renyi on 16/6/17.
//
#include "Client.h"

SSL * init_ssl_client(void){
    int sockfd, len;
    struct sockaddr_in dest;
    SSL_CTX *ctx;
    SSL *ssl;

    ctx = SSL_CTX_new(SSLv23_client_method());
    if (ctx == NULL) {
        ERR_print_errors_fp(stdout);
        exit(1);
    }

    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("Client Socket");
        exit(errno);
    }
    printf("Client socket created\n");

    bzero(&dest, sizeof(dest));
    dest.sin_family = AF_INET;
    dest.sin_port = htons(XLPORT);


    if (inet_aton(XLIP, (struct in_addr *) &dest.sin_addr.s_addr) == 0) {
        perror(XLIP);
        exit(errno);
    }
    printf("Client address created\n");
    if (connect(sockfd, (struct sockaddr *) &dest, sizeof(dest)) != 0) {
        perror("Connect ");
        exit(errno);
    }
    printf("Client server connected\n");

    ssl = SSL_new(ctx);
    SSL_set_fd(ssl, sockfd);

    if (SSL_connect(ssl) == -1)
        ERR_print_errors_fp(stderr);
    else {
        printf("Client connected with %s encryption\n", SSL_get_cipher(ssl));
    }

    return ssl;
}